package com.zm.demo.netty.server.count;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.CharsetUtil;

import static io.netty.util.CharsetUtil.UTF_8;
import static java.lang.System.out;

@ChannelHandler.Sharable
public class CountServerHander extends ChannelInboundHandlerAdapter {

    private int count = 0;
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf)msg;
        byte[] dst = new byte[in.readableBytes()];
        in.readBytes(dst, 0, in.readableBytes());
        out.println("Server object: " + new String(dst));
        ctx.write(Unpooled.copiedBuffer(String.valueOf(++count), UTF_8));
//        ctx.write(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }
}
